package com.topisv.tms.service.shipped;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.ShippedBoxSkus;
import com.topisv.tms.entity.work.WorkTaskItem;
import com.topisv.tms.repository.ShippedBoxSkusDao;
import com.topisv.tms.repository.work.WorkTaskItemDao;

@Component
@Transactional(readOnly = true)
public class ShippedBoxSkusService {

	@Autowired
	private ShippedBoxSkusDao shippedBoxSkusDao;
	@Autowired
	private WorkTaskItemDao workTaskItemDao;
	
	public Map<String, Integer> getShippedBoxSkus(String backupTaskCode){
		List<WorkTaskItem> workTaskItems=this.workTaskItemDao.loadByTaskCode(backupTaskCode);
		Map<String, Integer> allSkuMaps=new HashMap<String, Integer>();//已经拣货的sku汇总
		//得到未装箱的sku
		Map<String, Integer> noSkuMaps=new HashMap<String, Integer>();
		for(WorkTaskItem w:workTaskItems){
			if("unpicked".equals(w.getPickStatus())){
				continue;
			}
			String sku=w.getSku();
			int num=w.getPickedNum();
			if(num>0){
				if(allSkuMaps.get(sku)==null){
					allSkuMaps.put(sku, num);
				}else{
					allSkuMaps.put(sku, num+allSkuMaps.get(sku));
				}
			}
		}
		if(allSkuMaps.isEmpty()){
			return noSkuMaps;
		}
		List<ShippedBoxSkus> shippedBoxSkus=shippedBoxSkusDao.findByBackupTaskCode(backupTaskCode);
		Map<String, Integer> boxSkuMaps=new HashMap<String, Integer>();//已经装箱的sku汇总
		if(!shippedBoxSkus.isEmpty()){
			for(ShippedBoxSkus bs:shippedBoxSkus){
				String sku=bs.getSkuId();
				int num=bs.getRealQty();
				if(bs.getBoxCode()!=null){
					if(boxSkuMaps.get(sku)==null){
						boxSkuMaps.put(sku, num);
					}else{
						boxSkuMaps.put(sku, num+boxSkuMaps.get(sku));
					}
				}
			}
		}
		
		

		for(String allKey:allSkuMaps.keySet()){
			if(boxSkuMaps.get(allKey)==null){
				noSkuMaps.put(allKey, allSkuMaps.get(allKey));
			}else{
				if(allSkuMaps.get(allKey)>boxSkuMaps.get(allKey)){
					noSkuMaps.put(allKey, allSkuMaps.get(allKey)-boxSkuMaps.get(allKey));
				}
			}
		}
		
		return noSkuMaps;
	}


	public List<ShippedBoxSkus> findByBoxCodeAndBackupTaskCode(String boxCode,String backupTaskCode) {
		return shippedBoxSkusDao.findByBoxCodeAndBackupTaskCode(boxCode,backupTaskCode);
	}

	public List<ShippedBoxSkus> findByBoxCode(String boxCode) {
		return shippedBoxSkusDao.findByBoxCode(boxCode);
	}

	public ShippedBoxSkus findByBoxCodeAndSkuId(String boxCode, String skuId) {
		return shippedBoxSkusDao.findByBoxCodeAndSkuId(boxCode, skuId);
	}

	@Transactional(readOnly = false)
	public List<ShippedBoxSkus> save(List<ShippedBoxSkus> agr0) {
		return (List<ShippedBoxSkus>) shippedBoxSkusDao.save(agr0);
	}

	@Transactional(readOnly = false)
	public ShippedBoxSkus save(ShippedBoxSkus agr0) {
		return shippedBoxSkusDao.save(agr0);
	}

	
}
